<template>
  <div class="mod-sys__user">
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="getList()">
      <el-form-item label="学号">
        <el-input v-model="state.dataForm.userName" placeholder="学号" clearable></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="state.dataForm.realName" placeholder="姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="专业">
        <el-select v-model="state.dataForm.majorId" clearable>
          <el-option v-for="item in majorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="state.hasPermission('cam:admin')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-upload class="upload-demo" action="#" :before-upload="beforeUpload" :show-file-list="false"
          accept=".xlsx, .xls">
          <el-button v-if="state.hasPermission('cam:admin')" class="button" type="success">导入</el-button>
        </el-upload>
        <!-- <el-button type="info" @click="state.exportHandle()">导入</el-button> -->
      </el-form-item>
    </el-form>
    <TableWrapper :valueData="pageList" :columns="columns" :optrations="admin ? optrations : ''" @pageSize="pageSize"
      @currentPage="currentPage" :pageCurrent="{...pageCurrent,total}">
      <template #gender="{ row }">{{ state.getDictLabel("gender", row.gender) }}</template>
      <template #majorId="{ row }">{{ getMajorName(row.majorId) }}</template>
      <!-- <el-table-column prop="gender" label="性别" sortable="custom" header-align="center" align="center">
                <template v-slot="scope">
                  {{ state.getDictLabel("gender", scope.row.gender) }}
                </template>
      </el-table-column>-->
    </TableWrapper>
    <add-or-update ref="addOrUpdateRef" :majorList="majorList" @refreshDataList="getList()"></add-or-update>
  </div>
</template>

<script lang="ts" setup>
  import useView from "@/hooks/useView";
  import { reactive, ref, toRefs, onMounted } from "vue";
  import TableWrapper from "@/components/table/TableWrapper.vue";
  import AddOrUpdate from "./user-add-or-update.vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import baseService from "@/service/baseService";
  import XLSX from 'xlsx'
  const majorList = ref([]);
  const pageList = ref([]);
  const view = reactive({
    getDataListIsPage: true,
    deleteURL: "/sys/user",
    deleteIsBatch: true,
  });
  const state = reactive({ ...useView(view), ...toRefs(view) });
  const admin = ref(state.hasPermission("cam:admin"));
  const total = ref("0");
  const pageCurrent = reactive({
    pageNum: "1",
    pageSize: 20
  });
  const columns = ref([
    {
      value: "userName",
      label: "学号"
    },
    {
      value: "realName",
      label: "姓名"
    },
    {
      value: "gender",
      label: "性别"
    },
    {
      value: "className",
      label: "班级"
    },
    {
      value: "majorId",
      label: "专业"
    },
    {
      value: "mobile",
      label: "联系方式"
    }
  ]);
  const optrations = [
    {
      name: "编辑",
      type: "primary",
      icon: "el-icon-plus",
      method: (columns, row) => {
        addOrUpdateHandle(row);
      },
      disabled: false
    },
    {
      name: "删除",
      type: "danger",
      icon: "el-icon-plus",
      method: async (columns, row) => {
        await state.deleteHandle(row.id);
        getList();
      },
      disabled: false
    }
  ];

  onMounted(() => {
    getList();
    getMajorsList();
  });
  const getList = () => {
    let param = {
      ...pageCurrent,
      query: {
        userName: state.dataForm.userName,
        majorId: state.dataForm.majorId,
        realName: state.dataForm.realName
      }
    };
    baseService
      .post("/cam/user/pageStudent", param)
      .then((res) => {
        if (res.code === 0) {
          pageList.value = res.data.records;
          total.value = res.data.total;
        } else {
          ElMessage.error(res.msg);
        }
      })
      .catch(() => { });
  };
  // 获取专业列表
  const getMajorsList = () => {
    let param = {
      name: ""
    };
    baseService
      .post("/cam/major/getList", param)
      .then((res) => {
        if (res.code === 0) {
          majorList.value = res.data;
        } else {
          ElMessage.error(res.msg);
        }
      })
      .catch(() => { });
  };
  const pageSize = (val) => {
    pageCurrent.pageSize = val;
    getList();
  };
  const currentPage = (val) => {
    pageCurrent.pageNum = val;
    getList();
  };
  const addOrUpdateRef = ref();
  const addOrUpdateHandle = (row?: object) => {
    addOrUpdateRef.value.init(row);
  };
  const getMajorName = (id) => {
    if (majorList.value.length > 0) {
      return majorList.value.find((item) => {
        return item.id === id;
      }).name;
    }
  };
  const getMajorId = (name) => {
    if (majorList.value.length > 0) {
      const data = majorList.value.find((item) => {
        return item.name === name;
      });
      if (data) {
        return data.id
      }
      else {
        return ''
      }
    }
  };
  const beforeUpload = (file) => {
    file2XLSX(file).then((res) => {
      const data = res[0].sheet
      const exData = {
        username: "学号",
        majorId: '专业',
        className: "班级",
        password: "密码",
        confirmPassword: "确认密码",
        realName: "姓名",
        gender: "性别",
        mobile: "手机号",
      };

      const mapData = data.map(obj => {
        // 如果导入数据中专业不对 则不调用导入接口
        const MajorId = getMajorId(obj[exData.majorId])
        if (!MajorId) {
          ElMessage.error({
            message: '导入数据中部分专业不存在,请检查数据',
            duration: 2000  // 持续时间为 2000 毫秒
          });
        }
        return {
          username: obj[exData.username],
          majorId: MajorId,
          className: obj[exData.className],
          password: obj[exData.password],
          confirmPassword: obj[exData.confirmPassword],
          realName: obj[exData.realName],
          gender: obj[exData.gender] === "男" ? "0" : obj[exData.gender] === "女" ? '1' : '',
          mobile: obj[exData.mobile],
        };
      });
      if (mapData.every(el => el.majorId)) {
        baseService
          .post("/cam/user/batchAdd", mapData)
          .then((res) => {
            if (res.code === 0) {
              ElMessage.success('导入成功');
              getList();
            } else {
              ElMessage.error(res.msg);
            }
          })
          .catch(() => { });

      }
    })
    return false
  }
  const file2XLSX = (file) => {
    return new Promise(function (resolve, reject) {
      // 通过FileReader对象读取文件
      const reader = new FileReader()
      // 读取为二进制字符串
      reader.readAsBinaryString(file)
      reader.onload = function (e) {
        // 获取读取文件成功的结果值
        const data = e.target.result
        // XLSX.read解析数据，按照type 的类型解析
        let wb = XLSX.read(data, {
          type: 'binary' // 二进制
        })
        // 存储获取到的数据
        const result = []
        // 工作表名称的有序列表
        // console.log(wb)
        wb.SheetNames.forEach(sheetName => {
          result.push({
            // 工作表名称
            sheetName: sheetName,
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
          })
        })
        resolve(result)
      }
    })
  }
</script>